package cn.cq.admin.service.impl;

import cn.cq.admin.entity.dto.UserCourseBatchDto;
import cn.cq.admin.entity.model.*;
import cn.cq.admin.entity.vo.CourseVo;
import cn.cq.admin.entity.vo.UserCourseBatchVo;
import cn.cq.admin.service.*;
import cn.cq.common.BaseConst;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cq.admin.mapper.UserCourseBatchMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author  dicraft
 * @description 针对表【user_course_batch】的数据库操作Service实现
 */
@Service
public class UserCourseBatchServiceImpl extends ServiceImpl<UserCourseBatchMapper, UserCourseBatch>
        implements UserCourseBatchService {
    @Resource
    private BatchService batchService;
    @Resource
    private TUserService userService;
    @Resource
    private CourseService courseService;
    @Resource
    private BatchCourseService batchCourseService;
    @Resource
    private CoursewareService coursewareService;
    @Resource
    private UserCourseCoursewareService userCourseCoursewareService;
    @Override
    public Page<UserCourseBatchVo> doList(UserCourseBatchDto userCourseBatchDto) {
        String batchName = userCourseBatchDto.getBatchName();
        String actualName = userCourseBatchDto.getActualName();
        Page<UserCourseBatch> page = new Page<>(userCourseBatchDto.getPageNo(), userCourseBatchDto.getPageSize());

        List<UserCourseBatchVo> collect = lambdaQuery().like(StrUtil.isNotBlank(batchName), UserCourseBatch::getBatchName, batchName)
                .like(StrUtil.isNotBlank(actualName), UserCourseBatch::getActualName, actualName)
                .page(page)
                .getRecords()
                .stream()
                .map(userCourseBatch -> {
                    UserCourseBatchVo userCourseBatchVo = new UserCourseBatchVo();
                    userCourseBatchVo.setUserId(String.valueOf(userCourseBatch.getUserId()));
                    userCourseBatchVo.setBatchId(String.valueOf(userCourseBatch.getBatchId()));
                    userCourseBatchVo.setActualName(userCourseBatch.getActualName());
                    userCourseBatchVo.setBatchName(userCourseBatch.getBatchName());
                    userCourseBatchVo.setId(String.valueOf(userCourseBatch.getId()));
                    return userCourseBatchVo;
                })
                .collect(Collectors.toList());
        Page<UserCourseBatchVo> voPage = new Page<>();
        voPage.setRecords(collect);
        voPage.setTotal(page.getTotal());
        voPage.setSize(page.getSize());
        voPage.setCurrent(page.getCurrent());
        return voPage;
    }

    @Override
    public void doSave(UserCourseBatchDto userCourseBatchDto) {

        //封装数据集合
        List<UserCourseBatch> userCourseBatches = new ArrayList<>();
        List<Long> userIds = userCourseBatchDto.getUserIds();
        List<Long> batchIds = userCourseBatchDto.getBatchIds();
        //查询batchName
        List<Batch> batches = batchService.listByIds(batchIds);
        List<TUser> users = userService.listByIds(userIds);
        //查询actualName
        for (Long userId : userIds) {
            //根基userId查找actualName
            String actualName = null;
            for (TUser user : users) {
                if (user.getId().equals(userId)) {
                    actualName = user.getActualName();
                    break;
                }
            }
            for (Long batchId : batchIds) {
                //根据batchId查找batchName
                String batchName = null;
                for (Batch batch : batches) {
                    if (batch.getId().equals(batchId)) {
                        batchName = batch.getBatchName();
                        break;
                    }
                }
                UserCourseBatch userCourseBatch = new UserCourseBatch();
                userCourseBatch.setBatchId(batchId);
                userCourseBatch.setUserId(userId);
                userCourseBatch.setBatchName(batchName);
                userCourseBatch.setActualName(actualName);
                userCourseBatches.add(userCourseBatch);
            }
        }
        saveBatch(userCourseBatches);
        //TODO 使用多线程完成
        //新增user_course_courseware
        //通过批次查询课程 课件
        List<BatchCourse> batchCourses = batchCourseService.lambdaQuery().in(BatchCourse::getBatchId, batchIds).list();
        //通过课程id查找课件
        List<UserCourseCourseware> arrayList = new ArrayList<>();
        batchCourses.forEach(batchCourse -> {
            Long courseId = batchCourse.getCourseId();
            List<Courseware> coursewares = coursewareService.lambdaQuery().eq(Courseware::getCourseId, courseId).list();
            coursewares.forEach(courseware -> {
                userIds.forEach(userId -> {
                    UserCourseCourseware userCourseCourseware = new UserCourseCourseware();
                    userCourseCourseware.setCourseId(courseId);
                    userCourseCourseware.setEnd(0);
                    userCourseCourseware.setUserId(userId);
                    userCourseCourseware.setCoursewareId(courseware.getId());
                    arrayList.add(userCourseCourseware);
                });
            });
        });
        userCourseCoursewareService.saveBatch(arrayList);
    }

    @Override
    @Transactional
    public void doModify(UserCourseBatchDto userCourseBatchDto) {
        //根据用户id删除批次
        lambdaUpdate().eq(UserCourseBatch::getUserId, userCourseBatchDto.getUserId()).remove();
        //重新上传
        doSave(userCourseBatchDto);

    }

    @Override
    @Transactional
    public void doRemove(List<Long> ids) {
        removeBatchByIds(ids);
        //根据ids查找userId
        List<Long> collect = listByIds(ids)
                .stream()
                .map(UserCourseBatch::getUserId)
                .collect(Collectors.toList());
        userCourseCoursewareService.removeBatchByIds(collect);
    }

    @Override
    public List<CourseVo> doListCourseByUser(Long id) {
        //查询courseId
        List<Long> courseIds = lambdaQuery()
                .eq(UserCourseBatch::getUserId, id)
                .list()
                .stream()
                .map(UserCourseBatch::getCourseId)
                .collect(Collectors.toList());
        //根据courseId查询课程
        List<CourseVo> courseVos = courseService.lambdaQuery().in(Course::getId, courseIds)
                .eq(Course::getStatus, BaseConst.STATUS_ENABLE)
                .list()
                .stream()
                .map(course -> {
                    CourseVo courseVo = new CourseVo();
                    courseVo.setCourseName(course.getCourseName());
                    courseVo.setStatus(course.getStatus());
                    courseVo.setSort(course.getSort());
                    courseVo.setId(String.valueOf(course.getId()));
                    return courseVo;
                })
                .collect(Collectors.toList());
        return courseVos;
    }
}




